/**
 * Module dependencies.
 */
const express = require('express')
const bodyParser = require('body-parser')
const winston = require('winston')
const path = require('path')
const morgan = require('morgan')
const cookieParser = require('cookie-parser')

const _conf = require('./configs/configure')

const app = express()

// winston logger with console transport only
winston.configure({
  transports: [
    new winston.transports.Console({
      level: 'debug',
      format: winston.format.combine(
        winston.format.colorize({ all: true }),
        winston.format.splat(),
        winston.format.timestamp({ format: 'YYYY-MM-DD HH:mm:ss' }),
        winston.format.printf(({ level, message, timestamp }) => {
          return `[${timestamp}] [${level}] ${message}`
        })
      )
    })
  ]
})

if (app.get('env') === 'production') {
  winston.info('running in production mode !')
  app.use(morgan('tiny', {
    stream: { write: msg => winston.info(msg.trim()) }
  }))
  winston.add(
    new winston.transports.File({
      filename: 'error.log',
      level: 'error',
      format: winston.format.combine(
        winston.format.timestamp({ format: 'YYYY-MM-DD HH:mm:ss' }),
        winston.format.splat(),
        winston.format.json()
      )
    })
  )
  winston.add(
    new winston.transports.File({
      filename: 'combine.log',
      format: winston.format.combine(
        winston.format.timestamp({ format: 'YYYY-MM-DD HH:mm:ss' }),
        winston.format.splat(),
        winston.format.json()
      )
    })
  )
}

if (app.get('env') === 'development') {
  winston.info('running in development mode !')
  app.use(morgan('dev', {
    stream: { write: msg => winston.info(msg.trim()) }
  }))
}

// view engine setup
app.set('view engine', 'ejs')
app.set('views', path.join(__dirname, 'views'))

app.use(bodyParser.json())
app.use(express.json())
app.use(express.urlencoded({ extended: true }))
app.use(cookieParser())
app.use(express.static(path.join(__dirname, 'assets')))

app.use('/', require('./routes/index'))
;   // Ending symbols for app.set and app.use !

(async () => {
  try {
    var server = app.listen(_conf.port, () => {
      var host = server.address().host
      var port = server.address().port
      winston.info('Dashboard started at http://%s:%s', host, port)
    })
  } catch (e) {
    winston.error('Initialization failure !', e)
  }
})()
